package com.wingsfrog.travel.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wingsfrog.travel.base.BaseController;
import com.wingsfrog.travel.controller.dto.request.CheckTaskCompleteDto;
import com.wingsfrog.travel.controller.dto.response.*;
import com.wingsfrog.travel.modules.dao.*;
import com.wingsfrog.travel.modules.entity.*;
import com.wingsfrog.travel.service.TaskService;
import com.wingsfrog.travel.service.TeamHintService;
import com.wingsfrog.travel.service.TeamService;
import com.wingsfrog.travel.service.TeamTaskService;
import com.wingsfrog.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by rankin on 16/4/2.
 */
@RestController
@RequestMapping(value = "teamTask")
public class TeamController extends BaseController {
    @Autowired
    TaskDao taskDao;
    @Autowired
    TeamTaskDao teamTaskDao;
    @Autowired
    TeamDao teamDao;
    @Autowired
    TeamTaskService teamTaskService;
    @Autowired
    HintDao hintDao;
    @Autowired
    TeamHintDao teamHintDao;
    @Autowired
    TeamService teamService;
    @Autowired
    UserTeamRelDao userTeamRelDao;
    @Autowired
    TeamHintService teamHintService;
    @Autowired
    TaskService taskService;
    @Autowired
    UserDao userDao;

    @RequestMapping(value = "acceptTask", method = {RequestMethod.POST})
    @Transactional
    public Object acceptTask() throws Exception {
        return taskService.accpetTask();
    }

    @RequestMapping(value = "acceptHint")
    public Object acceptHind() throws Exception {
        UserTeamRel rel = userTeamRelDao.findByUserIdAndIsEnable(SessionUtil.getUserId(), true);
        if (rel == null) throw new Exception("not data found");
        Integer mainTaskId = rel.getMainTaskId();
        TeamTask teamTask = teamTaskService.getLastTeamTask(rel.getTeamId());
        if (teamTask == null) throw new Exception("没有任务");
        if (teamTask.getFinished() == 1) throw new Exception("任务已完成");

        return teamHintService.acceptHintByTeamTaskIdAndTaskId(teamTask.getTaskId(), teamTask.getId());
    }

    @RequestMapping(value = "check", method = {RequestMethod.POST})
    @Transactional
    public Object checkIsComplete(@RequestBody CheckTaskCompleteDto reqDto) throws Exception {
        //todo 检查是否满足要求
        UserTeamRel rel = userTeamRelDao.findByUserIdAndIsEnable(SessionUtil.getUserId(), true);
        if (rel == null) throw new Exception("not data found");
        Integer mainTaskId = rel.getMainTaskId();
        TeamInfo team = teamService.findTeamByMainTaskAndUser(mainTaskId, SessionUtil.getUserId());
        Integer teamId = team.getId();
        //找到最后一个任务，确认是已完成，并且不是终结任务
        TeamTask lastTask = teamTaskService.getLastTeamTask(teamId);
        if (lastTask == null) throw new Exception("没有这个任务");
        if (lastTask.getFinished() == (byte) 1) throw new Exception("任务已完成");

        UserTeamRel userTeamRel = userTeamRelDao.findByMainTaskIdAndUserId(mainTaskId, SessionUtil.getUserId());
        if (userTeamRel == null) throw new Exception("不存在队伍关联信息");
        userTeamRel.setLat(reqDto.getLat());
        userTeamRel.setLon(reqDto.getLon());
        userTeamRelDao.save(userTeamRel);

        CheckTaskResDto resDto = new CheckTaskResDto();

        CheckTaskCompleteDto check = (new Gson()).fromJson(lastTask.getCheckpoint(), new TypeToken<CheckTaskCompleteDto>() {
        }.getType());
        resDto.setAimLat(check.getLat());
        resDto.setAimLon(check.getLon());
        resDto.setAimName(check.getName());


        double aim_lat_beg = check.getLat() - 0.3;
        double aim_lat_end = check.getLat() + 0.3;
        double aim_lon_beg = check.getLon() - 0.3;
        double aim_lon_end = check.getLon() + 0.3;

        Boolean isComplete = true;
        List<UserPositionResDto> users = new ArrayList<>();
        List<UserTeamRel> relList = userTeamRelDao.findByTeamId(teamId);
        //todo 里面人不够
        for (UserTeamRel r : relList) {
            double check_lat = r.getLat();
            double check_lon = r.getLon();
            UserPositionResDto user = new UserPositionResDto();
            user.setLon(r.getLon());
            user.setLat(r.getLat());

            User u = userDao.findOne(r.getUserId());
            if (u == null) throw new Exception("成员中有不存在的人");
            user.setHeadimg(u.getHeadimg());
            user.setBrif(u.getBrif());

            if (!(check_lat >= aim_lat_beg || check_lat <= aim_lat_end) &&
                    !(check_lon >= aim_lon_beg || check_lon <= aim_lon_end)
                    ) {
                isComplete = false;
                user.setIsArrive(false);
            } else {
                user.setIsArrive(true);
            }
            users.add(user);
        }
        resDto.setUsers(users);

        if (isComplete) {
//            lastTask.setFinished((byte) 1);
//            teamTaskDao.save(lastTask);
//
//            rel.setIsEnable(false);
//            userTeamRelDao.save(rel);
        }
        return resDto;
    }

    @RequestMapping(value = "{teamId}/completeTask", method = {RequestMethod.POST})
    public Object completeTask(@PathVariable Integer teamId) {
        //完成当前任务
        return null;
    }

    @RequestMapping(value = "performTask", method = {RequestMethod.GET})
    public Object getPerformTask() throws Exception {

        UserTeamRel rel = userTeamRelDao.findByUserIdAndIsEnable(SessionUtil.getUserId(), true);
        if (rel == null) throw new Exception("not data found");
        Integer mainTaskId = rel.getMainTaskId();

        Integer teamId = rel.getTeamId();

        //获取当前执行的任务信息
        PerformTaskResDto resDto = new PerformTaskResDto();

        TeamTask lastTask = teamTaskService.getLastTeamTask(teamId);
        if (lastTask == null) return new BaseResDto(1, "需接受任务");
        if (lastTask.getFinished() == (byte) 1) {
            //如果最后一个任务是已完成，检查一下后续还有没有任务。
            Task taskToAccept = taskDao.findByMainTaskIdAndSequence(mainTaskId, lastTask.getSequence() + 1);
            if (taskToAccept == null) throw new Exception("任务已经全部完成");
            else return new BaseResDto(1, "需接受任务");
        }

        TaskResDto task = new TaskResDto(lastTask);
        List<TaskHintResDto> hints = new ArrayList<>();
        teamHintDao.findByTeamTaskId(lastTask.getId()).forEach(hint -> hints.add(new TaskHintResDto(hint)));
        task.setHintList(hints);

        List<TeamInfo> teams = teamDao.findByMainTaskId(mainTaskId);
        resDto.setTotalTeam(teams.size());
        //排序 todo
        for (int i = 1; i <= teams.size(); i++) {
            if (Objects.equals(teams.get(i - 1).getId(), teamId))
                resDto.setRank(i);
        }

        Long progress = teamTaskDao.getCountByTeamId(teamId);
        Long totalTask = taskDao.getCountByMainTaskId(mainTaskId);
        Hint hint = hintDao.findTop1ByTaskIdOrderByHintLevelDesc(lastTask.getTaskId());
        Integer hintMaxLevel = hint == null ? 0 : hint.getHintLevel();

        resDto.setMaxHintLevel(hintMaxLevel);
        resDto.setProgress(progress);
        resDto.setTotalTask(totalTask);
        resDto.setTask(task);
        return resDto;
    }
}
